<?php


namespace app\admin\controller;


use app\admin\validate\AdminUser as AdminUserValidate;
use app\BaseController;
use app\common\business\AdminUserBusiness;
use app\common\business\AdminUserSessionBusiness;
use think\facade\Request;
use think\facade\View;

class Login extends AdminBase
{
//    protected function initialize()
//    {
//        parent::initialize();
//        if (!AdminUserSessionBusiness::isNotLogin()) {
//            return $this->redirect(url("/admin/index"));
//        }
//    }
    public function index()
    {
        return View::fetch("index");
    }
    public function check()
    {
//        dump(Request::param());
        if (!Request::isPost()) {
            return show(config("status.error"), "请求方式错误");
        }

        $username = Request::param("username");
        $password = Request::param("password");
        $captcha = Request::param("captcha");

//        if (empty($username) || empty($password) || empty($captcha))
//        {
//            return show(config("status.error"), "参数异常");
//        }
//
//        if (!captcha_check($captcha))
//        {
//            return show(config("status.error"), "验证码错误");
//        }
         $validate = new AdminUserValidate();

         if (!$validate->check([
             'username' => $username,
             'password' => $password,
             'captcha' => $captcha
         ])){
             return show(config("status.error"), $validate->getError());
         }
        $adminUserBusiness = new AdminUserBusiness();
        $user = $adminUserBusiness->findUserByName($username);
//        dd($user);

        if (empty($user) || ($user['status']) != 1){
            return show(config("status.error"), "用户不存在");
        }

        if (!$adminUserBusiness->authenticate($password, $user)){
            return show(config("status.error"), "密码错误");
        }

        AdminUserSessionBusiness::setLoginUser($user);
        return show(config("status.success"), "登录成功");
    }
}